<?php

namespace App\Models\News;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\AdminUser;
use App\Models\News\NewsClass;
use App\Models\News\NewsContent;
use App\Models\News\NewsTag;
use App\Models\News\NewsArtist;
use App\Models\Artists\Artist;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Storage;
// use Laravel\Scout\Searchable;
use App\Helper\OpenSearch\Search;
class News extends Model
{
    //
    use SoftDeletes;
	// use Searchable;
	protected $table = 'news';

	protected $casts = [
        'attr' => 'json'
    ];
	
	public static $status = ['0' => '待审核','1' => '审核未通过', '2'=> '审核通过'];
	public static function boot() {
        parent::boot();
        static::saving(function($model) {
			if(Admin::user())$model->admin_edit_user_id = Admin::user()->id;
			if($model->titlepic)$model->titlepic = thumbOssTitlepicUrl($model->titlepic);
        });
		static::creating(function($model) {

			if(Admin::user())$model->admin_user_id = Admin::user()->id;
			
        });
        static::deleted(function($model) {
        	//删除静态文件
        	Storage::disk('build')->delete($model->titleurl);
        });
        
        
    }
    //栏目名称
    public function news_class()
    {
        return $this->hasOne(NewsClass::class,'id','class_id');
    }
	//发布人
	public function admin_user()
	{
		return $this->hasOne(AdminUser::class, 'id', 'admin_user_id');
	}
	//最后更新人
	public function admin_edit_user()
	{
		return $this->hasOne(AdminUser::class, 'id', 'admin_edit_user_id');
	}
	//艺术家
	public function artists()
    {
        return $this->belongsToMany(Artist::class, 'news_artists', 'new_id');
    }
    //关键词
	public function tags()
    {
        return $this->belongsToMany(Tag::class, 'news_tags', 'new_id');
    }
	
	//内容
	public function content()
	{
		return $this->hasOne(NewsContent::class, 'new_id', 'id');
	}
	public function getUrlAttribute()
	{
		if($this->titleurl)return $this->titleurl;
		return news_url($this->created_at, $this->id);
	}
}
